// utils/security.js
import CryptoJS from 'crypto-js'

const SECRET_KEY = 'SMART_LOCK_SECRET_KEY_2023'

/**
 * AES加密
 * @param {string} data - 需要加密的数据
 * @returns {string} 加密后的数据
 */
export const encrypt = (data) => {
  if (typeof data === 'object') {
    data = JSON.stringify(data)
  }
  const encrypted = CryptoJS.AES.encrypt(data, SECRET_KEY).toString()
  return encrypted
}

/**
 * AES解密
 * @param {string} encryptedData - 加密的数据
 * @returns {string|object} 解密后的数据
 */
export const decrypt = (encryptedData) => {
  try {
    const bytes = CryptoJS.AES.decrypt(encryptedData, SECRET_KEY)
    const decrypted = bytes.toString(CryptoJS.enc.Utf8)

    // 尝试解析为JSON对象
    try {
      return JSON.parse(decrypted)
    } catch {
      return decrypted
    }
  } catch (error) {
    console.error('解密失败:', error)
    return null
  }
}

/**
 * SHA256哈希
 * @param {string} data - 需要哈希的数据
 * @returns {string} 哈希值
 */
export const hash = (data) => {
  return CryptoJS.SHA256(data).toString()
}

/**
 * 生成随机密码
 * @param {number} length - 密码长度
 * @returns {string} 随机密码
 */
export const generateRandomPassword = (length = 6) => {
  const chars = '0123456789'
  let password = ''
  for (let i = 0; i < length; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return password
}

/**
 * 验证密码强度
 * @param {string} password - 密码
 * @returns {object} 验证结果
 */
export const validatePassword = (password) => {
  const result = {
    isValid: true,
    message: ''
  }

  if (!password) {
    result.isValid = false
    result.message = '密码不能为空'
    return result
  }

  if (password.length < 4) {
    result.isValid = false
    result.message = '密码长度不能少于4位'
    return result
  }

  if (password.length > 12) {
    result.isValid = false
    result.message = '密码长度不能超过12位'
    return result
  }

  if (!/^\d+$/.test(password)) {
    result.isValid = false
    result.message = '密码只能包含数字'
    return result
  }

  return result
}
